<template>
  <div class="main-card">
    <el-card class="box-card">
      <template #header>
        <span>定时任务</span>
      </template>
      <el-form ref="ruleForm" :model="queryParams" label-width="100px">
        <div class="search-form">
          <el-form-item label="任务名称">
            <el-input v-model="queryParams.jobName" clearable />
          </el-form-item>
          <el-form-item label="任务分组">
            <el-select v-model="queryParams.jobGroup" clearable placeholder="请选择">
                <el-option
                  v-for="dict in jobGroupOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                ></el-option>
              </el-select>
          </el-form-item>
          <el-form-item label="任务状态">
            <el-select v-model="queryParams.status" clearable placeholder="请选择">
              <el-option
                label="正常"
                :value="1"
              />
              <el-option
                label="暂停"
                :value="0"
              />
            </el-select>
          </el-form-item>
          <el-button style="margin-left: 20px" type="primary" @click="search">搜索</el-button>
        </div>
      </el-form>
      <div style="margin:20px 0;">
          <el-button v-hasPermi="['monitor:job:add']" style="margin-left: 20px" type="primary" icon="el-icon-plus" @click="addOrUpdate()">添加</el-button>
          <el-button v-hasPermi="['monitor:job:remove']" type="danger" icon="el-icon-delete" @click="deleteTask">删除</el-button>
          <el-button v-hasPermi="['monitor:job:query']" type="info" icon="el-icon-s-operation" @click="handleJobLog">日志</el-button>
      </div>
      <div>
        <el-table
          :data="dataList"
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
        <el-table-column
          type="selection"
          width="55"
        />
        <el-table-column
          prop="jobId"
          label="任务编号"
          width="120"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          prop="jobName"
          label="任务名称"
          width="120"
        />
        <el-table-column
          prop="jobGroup"
          label="任务组名"
          width="120"
          :formatter="jobGroupFormat"
        />
        <el-table-column
          prop="invokeTarget"
          label="调用目标字符串"
          width="200"
        />
        <el-table-column
          prop="cronExpression"
          label="cron执行表达式"
          width="120"
        />
        <el-table-column
          prop="status"
          label="状态"
          width="120"
        >
          <template #default="{row}">
            <el-switch v-model="row.status" @change="handleStatusChange(row)" />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="350">
          <template #default="{row}">
            <el-button v-hasPermi="['monitor:job:changeStatus']" type="primary" icon="el-icon-caret-right" @click="runTask(row)">执行一次</el-button>
            <el-button v-hasPermi="['monitor:job:edit']" type="primary" icon="el-icon-edit" @click="addOrUpdate(row)">修改</el-button>
            <el-button v-hasPermi="['monitor:job:remove']" type="danger" icon="el-icon-delete" @click="deleteTask(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        v-show="total>0"
        :current-page="queryParams.pageNum"
        :page-size="queryParams.pageSize"
        :total="total"
        @current-change="handleCurrentChange"
      />
      </div>
    </el-card>
    <au-timied-task :value="isAuTimiedTaskShow" @close="isAuTimiedTaskShow = false" @onRefresh="search"/>
  </div>
</template>

<script lang="ts">
import { toRefs, reactive, watchEffect, computed, defineComponent } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import moment from 'moment'
import { ElMessageBox, ElMessage } from 'element-plus'
import { selectDictLabel } from '@/utils'
import AuTimiedTask from './components/AuTimiedTask.vue'
import { DictData } from '@/store/modules/system/dictData'
import { StateType as TimedTaskStateType, Job } from '@/store/modules/monitor/timedTask'
import tableList, { BaseQueryType, BaseDataType } from '@/mixins/tableList'

interface QueryParamsType extends BaseQueryType{
  jobName: string;
  jobGroup: string;
  status: number | null;
  beginTime: string | null;
  endTime: string | null;
}

interface DataType extends BaseDataType<Job>{
  isAuTimiedTaskShow: boolean;
  queryParams: QueryParamsType;
  dateRange: Array<string>;
  jobGroupOptions: Array<DictData>;
}

export default defineComponent({
  components: { AuTimiedTask },
  name: 'TimedTask',
  setup() {
    const store = useStore<{timedTask: TimedTaskStateType}>()
    const router = useRouter()
    const data = reactive<DataType>({
      url: 'timedTask/getList',
      isAuTimiedTaskShow: false,
      dateRange: [],
      jobGroupOptions: [],
      dataList: [],
      selectList: [],
      total: 0,
      queryParams: {
        jobName: '',
        jobGroup: '',
        status: null,
        beginTime: null,
        endTime: null,
        pageNum: 1,
        pageSize: 10
      }
    })
    store.dispatch('timedTask/getJobGroupOptions')
    const jobGroupOptions = computed<Array<DictData>>(() => {
      return store.state.timedTask.jobGroupOptions
    })
    const {
      dateFormat,
      getList,
      handleSelectionChange,
      handleCurrentChange,
      search
    } = tableList(data)
    search.value()
    watchEffect(() => {
      if (data.dateRange && data.dateRange.length >= 2) {
        data.queryParams.beginTime = moment(data.dateRange[0]).format('YYYY-MM-DD')
        data.queryParams.endTime = moment(data.dateRange[1]).format('YYYY-MM-DD')
      } else {
        data.queryParams.beginTime = null
        data.queryParams.endTime = null
      }
    })
    const deleteTask = (row: Job) => {
      const ids = [row.jobId] || (data.selectList || []).map(item => item.jobId)
      if (!ids || ids.length === 0) {
        return
      }
      ElMessageBox.confirm('是否删除"' + ids + '"任务?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return store.dispatch('timedTask/delete', ids)
      }).then(() => {
        ElMessage({
          message: '删除成功',
          type: 'success'
        })
        getList.value()
      }).catch()
    }
    const jobGroupFormat = (row: Job) => {
      return selectDictLabel(jobGroupOptions.value, row.businessType)
    }
    const addOrUpdate = (row: Job) => {
      store.commit('timedTask/SET_DATA', row)
      data.isAuTimiedTaskShow = true
    }
    // 更改状态
    const handleStatusChange = (row: Job) => {
      const text = row.status ? '启用' : '停用'
      ElMessageBox.confirm('确认要' + text + '"' + row.jobName + '"任务吗?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return store.dispatch('timedTask/changeStatus', row)
      }).then(() => {
        ElMessage({
          message: '更改状态成功',
          type: 'success'
        })
        getList.value()
      }).catch(() => {
        row.status = !row.status
      })
    }
    const runTask = (row: Job) => {
      ElMessageBox.confirm('确认要立即执行一次"' + row.jobName + '"任务吗?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return store.dispatch('timedTask/run', row)
      }).then(() => {
        ElMessage({
          message: '执行成功',
          type: 'success'
        })
        getList.value()
      }).catch(() => {
        row.status = !row.status
      })
    }
    const handleJobLog = () => {
      router.push({
        name: 'TaskLog'
      })
    }
    return {
      dateFormat,
      handleSelectionChange,
      handleCurrentChange,
      search,
      ...toRefs(data),
      jobGroupOptions,
      jobGroupFormat,
      addOrUpdate,
      deleteTask,
      handleStatusChange,
      runTask,
      handleJobLog
    }
  }
})
</script>

<style lang="scss">
.el-pagination{
  margin-top: 20px;
}
</style>
